package co.yixiang.modules.supplier.service.impl;

import co.yixiang.modules.shop.domain.YxUser;
import co.yixiang.modules.shop.service.YxUserService;
import co.yixiang.modules.shop.service.dto.YxUserDTO;
import co.yixiang.modules.supplier.domain.SupplierUser;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.modules.supplier.repository.SupplierUserRepository;
import co.yixiang.modules.supplier.service.SupplierUserService;
import co.yixiang.modules.supplier.service.dto.SupplierUserDto;
import co.yixiang.modules.supplier.service.dto.SupplierUserQueryCriteria;
import co.yixiang.modules.supplier.service.mapper.SupplierUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import co.yixiang.utils.PageUtil;
import co.yixiang.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import javax.annotation.Resource;


/**
* @author Walert
* @date 2021-03-26
*/
@Service
//@CacheConfig(cacheNames = "supplierUser")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SupplierUserServiceImpl implements SupplierUserService {

    @Resource
    private SupplierUserRepository supplierUserRepository;
    @Resource
    private SupplierUserMapper supplierUserMapper;
    @Resource
    private YxUserService userService;

    @Override
    //@Cacheable
    public Map<String,Object> queryAll(SupplierUserQueryCriteria criteria, Pageable pageable){
        Page<SupplierUser> page = supplierUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(supplierUserMapper::toDto));
    }

    @Override
    //@Cacheable
    public List<SupplierUserDto> queryAll(SupplierUserQueryCriteria criteria){
        return supplierUserMapper.toDto(supplierUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public SupplierUserDto findById(Long id) {
        SupplierUser supplierUser = supplierUserRepository.findById(id).orElseGet(SupplierUser::new);
        ValidationUtil.isNull(supplierUser.getId(),"SupplierUser","id",id);
        return supplierUserMapper.toDto(supplierUser);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public SupplierUserDto create(SupplierUser resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        return supplierUserMapper.toDto(supplierUserRepository.save(resources));
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(SupplierUser resources) {
        SupplierUser supplierUser = supplierUserRepository.findById(resources.getId()).orElseGet(SupplierUser::new);
        ValidationUtil.isNull( supplierUser.getId(),"SupplierUser","id",resources.getId());
        supplierUser.copy(resources);
        supplierUserRepository.save(supplierUser);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            supplierUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SupplierUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SupplierUserDto supplierUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("登录账号(手机号)", supplierUser.getAccount());
            map.put("昵称", supplierUser.getNickName());
            map.put("姓名", supplierUser.getUserName());
            map.put("公司名称", supplierUser.getCompanyName());
            map.put("微信openId", supplierUser.getWechatOpenId());
            map.put("权限级别 0：游客 1：一级 2：二级 3：三级 4：零售", supplierUser.getLevel());
            map.put("是否删除 0：否 1：是", supplierUser.getIsDel());
            map.put("创建时间", supplierUser.getCreateTime());
            map.put("更新时间", supplierUser.getUpdateTime());
            map.put("更新用户", supplierUser.getUpdateUser());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void create(Long userId,String userName,String companyName, Integer level){
        YxUserDTO userDTO = userService.findById(userId.intValue());
        SupplierUserQueryCriteria criteria = new SupplierUserQueryCriteria();
        criteria.setUserId(userId);
        List<SupplierUserDto> supplierUserDtos = this.queryAll(criteria);
        if(supplierUserDtos != null || (supplierUserDtos != null && supplierUserDtos.size() == 0)){
            SupplierUser saveObj = new SupplierUser();
            saveObj.setUserName(userName);
            saveObj.setNickName(userDTO.getNickname());
            saveObj.setAccount(userDTO.getAccount());
            saveObj.setCompanyName(companyName);
            saveObj.setLevel(level);
            saveObj.setWechatOpenId(userDTO.getOpenId());
            saveObj.setIsDel(0);
            saveObj.setCreateTime(System.currentTimeMillis());
            saveObj.setUserId(userId);
            this.create(saveObj);
        }
    }
}

